from flask import Flask, make_response, render_template, request, Response
from kubernetes import client, config
from loguru import logger
import requests
import base64
import time

# Flask App
app = Flask(__name__, static_folder=None, static_url_path='/noonecanguessmystaticpath')


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def proxy(*args, **kwargs):
    logger.info(f'Get request to {request.url}')
    target_headers = {key: value for (key, value) in request.headers if key != 'Host'}

    if 'Serviceproxy' in target_headers:
        logger.info('Cycle connection.')
        return 'Ops! 检测到循环，请不要直接访问该URL。请在网络设置中，将http代理设置为本网址。'

    target_headers['Serviceproxy'] = '1'

    resp = requests.request(
        method=request.method,
        url=request.url,
        headers=target_headers,
        data=request.get_data(),
        cookies=request.cookies,
        allow_redirects=False,
        verify=False)

    excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
    headers = [(name, value) for (name, value) in resp.raw.headers.items()
               if name.lower() not in excluded_headers]

    response = Response(resp.content, resp.status_code, headers)
    logger.info(f'Status Code: {resp.status_code}')

    return response


if __name__ == '__main__':
    app.run('0.0.0.0', port=6789, debug=False)
